package servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.google.gson.Gson;

import common.CONST;
import common.ServerResponse;
import service.IProductService;
import service.impl.ProductServiceImpl;
import util.myUtil;

@WebServlet("/manage/product")
public class ProductServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		setHead(request,response);
		System.out.println("进入servlet");
		String type=request.getParameter("type");
		System.out.println("type:"+type);
		if("list".equals(type)) {
			list(request,response);
		}
		else if("search".equals(type)) {
			search(request,response);
		}
		else if("upload".equals(type)) {
			upload(request,response);
		}
		else if("detail".equals(type)) {
			detail(request,response);
		}
		else if("set_sale_status".equals(type)) {
			set_sale_status(request,response);
		}
		else if("save".equals(type)) {
			save(request,response);
		}
		else if("richtext_img_upload".equals(type)) {
			richtext_img_upload(request,response);
		}
		
		
	}
	
	
	//操作区////////////
		/*********************产品list*********************/
		protected void list(HttpServletRequest request, HttpServletResponse response) {
			System.out.println("进入产品list");
			String pageSize=request.getParameter("pageSize");
			String pageNum=request.getParameter("pageNum");
			System.out.println("数据为："+pageSize+" "+pageNum);
			//执行list逻辑
			IProductService productService = new ProductServiceImpl();
			ServerResponse se = productService.list(pageSize,pageNum);
			//将ServerResponse转为json并通过流写出
			getjson(se,response);
		}
		/*********************产品搜索*********************/
		protected void search(HttpServletRequest request, HttpServletResponse response) {
			String product_id=request.getParameter("product_id");
			String product_name=request.getParameter("product_name");
			String pageNum=request.getParameter("pageNum");
			String pageSize=request.getParameter("pageSize");
			//执行搜索逻辑
			IProductService productService = new ProductServiceImpl();
			ServerResponse se = productService.search(product_id,product_name,pageNum,pageSize);
			//将ServerResponse转为json并通过流写出
			getjson(se,response);
		}
		/*********************图片上传*********************/
		protected void upload(HttpServletRequest request, HttpServletResponse response) {
			String path="D:/eclipse/upload/pic/";
			String fn=null;
	        DiskFileItemFactory factory=new DiskFileItemFactory();
	        ServletFileUpload sfu=new ServletFileUpload(factory);
	        sfu.setHeaderEncoding("UTF-8");  //处理中文问题
	        sfu.setSizeMax(1024*1024*10);   //限制文件大小
	        
	        try {
	            List<FileItem> fileItems= sfu.parseRequest(request);  //解码请求 得到所有表单元素
	            for (FileItem fi : fileItems) {
	                //有可能是 文件，也可能是普通文字 
	                if (fi.isFormField()) { //这个选项是 文字 
	                    System.out.println("表单值为："+fi.getString());
	                }else{
	                    // 是文件
	                	//获取图片后缀名
	                    String format=fi.getName().substring(fi.getName().indexOf("."), fi.getName().length());
	                    //图片命名
	                    fn=UUID.randomUUID().toString().replaceAll("-", "")+format;
	                    System.out.println("文件名是："+fn);  //文件名 
	                    // fn 是可能是这样的 c:\abc\de\tt\fish.jpg
	                    fi.write(new File(path,fn));
	                    String mypath=fn;
	                    ServerResponse se=ServerResponse.serverResponseBySuccess(mypath,"ok:成功返回了图片的本地地址");
	                    myUtil.getjson(se,response);
	                }                
	            }    
	            
	        } catch (Exception e) {
	        	System.out.println("捕捉到异常：图片上传出现了错误！！！");
	            e.printStackTrace();
	        }
		}

		//产品详情
		protected void detail(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
			String product_id=request.getParameter("product_id");
			System.out.println("产品id"+product_id);
			IProductService p=new ProductServiceImpl();
			getjson(p.detail(product_id),response);
	}
		
		//产品上下架
		protected void set_sale_status(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
			String product_id=request.getParameter("product_id");
			String status=request.getParameter("status");
			IProductService p=new ProductServiceImpl();
			getjson(p.set_sale_status(product_id,status),response);
	}
		
		//新增OR更新产品
		protected void save(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
			String category_id=request.getParameter("category_id");
			String name=request.getParameter("name");
			String subtitle=request.getParameter("subtitle");
			String main_image=request.getParameter("main_image");
			String subImages=request.getParameter("subImages");
			String detail=request.getParameter("detail");
			String price=request.getParameter("price");
			String stock=request.getParameter("stock");
			String status=request.getParameter("status");
			String id=request.getParameter("id");
			IProductService p=new ProductServiceImpl();
			getjson(p.save(id,category_id,name,subtitle, main_image,subImages,detail,price,stock,status),response);
		
	}
		
		//富文本details上传
	protected void richtext_img_upload(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		  String product_id=request.getParameter("product_id");
		  String detail=request.getParameter("detail");
		  System.out.println("此时的product_id为："+product_id);
		  System.out.println("此时的富文本detail为："+detail);
		  IProductService p=new ProductServiceImpl();
		  myUtil.getjson(p.Richtext_img_upload(product_id, detail), response);
		  
	}	
	

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("进入dopost");
		doGet(request, response);
	}
	
	
	protected void getjson(ServerResponse se,HttpServletResponse response) {
		Gson gson=new Gson();
		String json=gson.toJson(se);
		PrintWriter pw;
		try {
			pw=response.getWriter();
			pw.write(json);
			pw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	
	
	protected void setHead(HttpServletRequest request,HttpServletResponse response) {
		//转发时候防止中文乱码
	    response.setHeader("content-type", "text/html;charset=UTF-8");
	    response.setCharacterEncoding("UTF-8");
	    String originHeader=request.getHeader("Origin");
		/* 允许跨域的主机地址 */ response.setHeader("Access-Control-Allow-Origin", originHeader);
		/* 允许跨域的请求方法GET, POST, HEAD 等 */ response.setHeader("Access-Control-Allow-Methods", "*"); 
		/* 重新预检验跨域的缓存时间 (s) */ response.setHeader("Access-Control-Max-Age", "3600");
		/* 允许跨域的请求头 */ response.setHeader("Access-Control-Allow-Headers", "*"); 
		/* 是否携带cookie */ response.setHeader("Access-Control-Allow-Credentials", "true");
		
		
	}

}
